﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;
using System.Xml;
using ChinaClipping.ClippingMaster.Controls;
using ChinaClipping.ClippingMaster.Model;
using System.Security;

namespace ChinaClipping.ClippingMaster.Editor
{
	public partial class ClippingEditor : Form
	{
		//private static Encoding _xmlFileEncoding = Encoding.Unicode;
		//private static string XMLTEMPLATE = "<?xml version=\"1.0\" encoding=\"Unicode\"?><Clipping><ContentHtml /><ContentTxt /><Pictures /><CapPictures /></Clipping>";

		private static Encoding _xmlFileEncoding = Encoding.UTF8;
		private static string XMLTEMPLATE = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Clipping><ContentHtml /><ContentTxt /><Pictures /><CapPictures /></Clipping>";

		private bool _startwithargs = false;
		private mshtml.IHTMLDocument2 ClippingHtml;
		private InstalledFontCollection _fonts = new InstalledFontCollection();
		private Dictionary<string, ClippingProperty> _controllist = new Dictionary<string, ClippingProperty>();

		private FtpInfo _ftp;
		private HttpInfo _http;
		private User _currentuser;
		private ClientInfo _selectedclient;
		private List<ClassInfo> _selectedclass;

		private bool _autoopenurl = false;
		private bool _autogetcontent = false;
		private bool _fullchannel = false;//值为true时，提取频道形如 首页>资讯中心，否则形如： 资讯中心

		static ClippingEditor()
		{ 
			_xmlFileEncoding = Encoding.GetEncoding(Properties.Settings.Default.ClippingEncoding);
            initXmlTemplate();
		}

        static void initXmlTemplate()
        {
            if (_xmlFileEncoding == Encoding.Unicode)
            {
                XMLTEMPLATE = "<?xml version=\"1.0\" encoding=\"Unicode\"?><Clipping><ContentHtml /><ContentTxt /><Pictures /><CapPictures /></Clipping>";
            }
            else if (_xmlFileEncoding == Encoding.UTF8)
            {
                XMLTEMPLATE = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Clipping><ContentHtml /><ContentTxt /><Pictures /><CapPictures /></Clipping>";
            }
            else
            {
                XMLTEMPLATE = string.Format("<?xml version=\"1.0\" encoding=\"{0}\"?><Clipping><ContentHtml /><ContentTxt /><Pictures /><CapPictures /></Clipping>", _xmlFileEncoding.WebName);
            }
        
        }
		public ClippingEditor()
		{
			InitializeComponent();
			LoadSharedPropertiesControl();
			this.splitContainer3.Panel1.MouseWheel += new MouseEventHandler(Panel1_MouseWheel);
			this.pictureBox1.MouseEnter += new EventHandler(pictureBox1_MouseEnter);
		}
       


		void pictureBox1_MouseEnter(object sender, EventArgs e)
		{
			pictureBox1.Focus();
		}

		void Panel1_MouseWheel(object sender, MouseEventArgs e)
		{
			var currentPosition = this.splitContainer3.Panel1.AutoScrollPosition;
			int y = currentPosition.Y + e.Delta;
			if (y > 0)
				y = 0;
			Point newPosition = new Point(Math.Abs(currentPosition.X), Math.Abs(y));
			this.splitContainer3.Panel1.AutoScrollPosition = newPosition;
		}

		public ClippingEditor(string headline, string publication, string date, string url)
			: this()
		{
			DateTime dt;
			if (DateTime.TryParse(date, out dt))
				_controllist["日期"].PropertyValue = dt.ToString("yyyy-MM-dd");
			_controllist["媒体"].PropertyValue = publication;
			_controllist["链接"].PropertyValue = url;
			if (!string.IsNullOrEmpty(headline))
			{
				this.Text = headline;
				_controllist["标题"].PropertyValue = headline;
			}
			this._startwithargs = true;
		}

		public ClippingEditor(string headline, string publication, string date, string url, User user, FtpInfo ftp)
			: this(headline, publication, date, url)
		{

			this._currentuser = user;
			this._ftp = ftp;
		}
		public ClippingEditor(string headline, string publication, string date, string url, User user, FtpInfo ftp, bool autoOpen, bool autoGetContent)
			: this(headline, publication, date, url, user, ftp)
		{
			_autogetcontent = autoGetContent;
			_autoopenurl = autoOpen;
		}

		public ClippingEditor(User user, FtpInfo ftp)
		{
			this._currentuser = user;
			this._ftp = ftp;
		}




		public ClippingEditor(string headline, string publication, string date, string url, User user, HttpInfo httpInfo)
			: this(headline, publication, date, url)
		{

			this._currentuser = user;
			this._http = httpInfo;
		}

		public ClippingEditor(string headline, string publication, string date, string url, User user, HttpInfo httpInfo, bool autoOpen, bool autoGetContent)
			: this(headline, publication, date, url, user, httpInfo)
		{
			_autogetcontent = autoGetContent;
			_autoopenurl = autoOpen;
		}

		public ClippingEditor(User user, HttpInfo httpInfo)
		{
			this._currentuser = user;
			this._http = httpInfo;
		}









		private void ClippingEditor_Load(object sender, EventArgs e)
		{
			// WB_Clipping.Navigate(Path.Combine (Application.StartupPath , "TempHtmlFile.html"));
			WB_Clipping.Navigate("about:blank");
			ClippingHtml = WB_Clipping.Document as mshtml.IHTMLDocument2;
			ClippingHtml.designMode = "On";
			LoadFonts();
			Bind();
			if (this._startwithargs)
			{

				if (Uri.IsWellFormedUriString(_controllist["链接"].PropertyValue, UriKind.Absolute))
				{
					if (this._autoopenurl)
						WB_NewsSite.Navigate(_controllist["链接"].PropertyValue);
					if (this._autogetcontent)
						WB_Clipping.NavigateComplete2 += new AxSHDocVw.DWebBrowserEvents2_NavigateComplete2EventHandler(WB_Clipping_NavigateComplete2);
				}

			}
		}

		void WB_Clipping_NavigateComplete2(object sender, AxSHDocVw.DWebBrowserEvents2_NavigateComplete2Event e)
		{
			string content;
			Uri nextpage;
			Cursor = Cursors.WaitCursor;
			Uri uri = new Uri(_controllist["链接"].PropertyValue);
			string channel;
			MyTools.NewsParser.GetContent(uri, 1, out content, out channel, out nextpage);
			if (ClippingHtml.body != null && content != null)
			{
				ClippingHtml.body.innerHTML = ClippingHtml.body.innerHTML + content;
			}
			if (!string.IsNullOrEmpty(channel) && !_fullchannel)
			{
				int index = channel.LastIndexOf(">");
				if (index > 0 && index < channel.Length - 1)
				{
					channel = channel.Substring(index + 1);
					channel = channel.Trim();
				}
			}
			_controllist["版面"].PropertyValue = channel;
			WB_Clipping.NavigateComplete2 -= WB_Clipping_NavigateComplete2;
			Cursor = Cursors.Default;
		}



		/// <summary>
		/// 加载剪报属性控件
		/// </summary>
		private void LoadSharedPropertiesControl()
		{

			ClippingProperty cp;
			cp = new ClippingProperty("标题", "headlineC");
			this.tableLayoutPanel1.Controls.Add(cp, 0, 0);
			cp.Dock = DockStyle.Fill;
			_controllist.Add("标题", cp);

			//cp = new ClippingProperty("链接", "link");
			cp = ClippingProperty.GetLinkClippingProperty("链接", "link");
			this.tableLayoutPanel1.Controls.Add(cp, 0, 1);
			cp.Dock = DockStyle.Fill;
			cp.KeyDown += new KeyEventHandler(cp_KeyDown);
			_controllist.Add("链接", cp);


			cp = new ClippingProperty("中文摘要", "synopsisC");
			cp.Multiline = true;
			this.tableLayoutPanel1.Controls.Add(cp, 0, 5);
			cp.Dock = DockStyle.Fill;
			cp.Height = 50;
			_controllist.Add("中文摘要", cp);
			string[][] properties = new string[][] { new string[] { "媒体", "mediaID" }, new string[] { "版面", "Section" }, new string[] { "日期", "mediaDate" }, new string[] { "记者", "Reporter" }, new string[] { "字数", "Words" }, new string[] { "广告值", "adValue" }, new string[] { "页面", "Page" }, new string[] { "宽度", "Width" }, new string[] { "高度", "Height" }, new string[] { "页面大小", "pageSize" } };
			foreach (string[] s in properties)
			{
				cp = new ClippingProperty(s[0], s[1]);
				if (s[0] == "版面")
					cp.Width = 405;
				else
					cp.Width = 200;
				this.flowLayoutPanel_PublicFields.Controls.Add(cp);
				_controllist.Add(s[0], cp);
			}
			_controllist["广告值"].PropertyValue = Properties.Settings.Default.DefaultAd;
			_controllist["页面"].PropertyValue = Properties.Settings.Default.DefaultPage;
			_controllist["宽度"].PropertyValue = Properties.Settings.Default.DefaultWidth;
			_controllist["高度"].PropertyValue = Properties.Settings.Default.DefaultHeight;
			_controllist["页面大小"].PropertyValue = Properties.Settings.Default.DefaultPagesize;
		}



		/// <summary>
		/// 加载字体
		/// </summary>
		private void LoadFonts()
		{
			foreach (FontFamily f in _fonts.Families)
			{
				TCB_Font.Items.Add(f.Name);
			}
		}

		private void Bind()
		{
			ToolStrip_Main.DataBindings.Add("Visible", TSM_ShowToolBar, "Checked");
			// statusStrip_Main.DataBindings.Add("Visible", TSM_ShowStatusBar, "Checked");
		}


		#region 菜单
		/// <summary>
		/// 退出
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSM_Exit_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		/// <summary>
		/// 撤销
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSM_Undo_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("undo", false, null);
		}
		/// <summary>
		/// 重复
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSM_Redo_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("redo", false, null);
		}
		/// <summary>
		/// 剪切
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSM_Cut_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("cut", false, null);
		}
		/// <summary>
		/// 复制
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSM_Copy_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("copy", false, null);
		}
		/// <summary>
		/// 粘贴
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSM_Paste_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("paste", false, null);
		}
		/// <summary>
		/// 纯文本粘贴
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSM_SelectPaste_Click(object sender, EventArgs e)
		{
			string tmpstr = Clipboard.GetText();
			mshtml.IHTMLTxtRange range = ClippingHtml.selection.createRange() as mshtml.IHTMLTxtRange;
			StringBuilder sb = new StringBuilder(tmpstr.Length + 2000);
			string[] strs = Regex.Split(tmpstr, @"[\r\n][\s　]*");
			foreach (string s in strs)
			{
				sb.Append("<P>    ");
				sb.Append(s);
				sb.AppendLine("</P>");
			}
			range.pasteHTML(sb.ToString());
		}

		/// <summary>
		/// 清除格式
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSM_ClearFormat_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("removeformat", false, null);
		}
		/// <summary>
		/// 删除
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSM_Delete_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("delete", false, null);
		}

		/// <summary>
		/// 全选
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSM_SelectAll_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("selectall", false, null);
		}
		/// <summary>
		/// 显示剪报
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSM_ShowClipping_Click(object sender, EventArgs e)
		{
			TSM_ShowClipping.Checked = true;
			TSM_ShowNewsSite.Checked = false;
			TabControl1.SelectedIndex = 0;
			ClippingHtml.parentWindow.focus();
		}
		/// <summary>
		/// 显示新闻
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSM_ShowNewsSite_Click(object sender, EventArgs e)
		{
			TSM_ShowNewsSite.Checked = true;
			TSM_ShowClipping.Checked = false;
			TabControl1.SelectedIndex = 1;
			WB_NewsSite.Focus();
		}

		private void TabControl1_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (TabControl1.SelectedIndex == 0)
			{
				TSM_ShowClipping.Checked = true;
				TSM_ShowNewsSite.Checked = false;
			}
			else
			{
				TSM_ShowClipping.Checked = false;
				TSM_ShowNewsSite.Checked = true;
			}

		}
		#endregion

		#region HTML编辑
		/// <summary>
		/// 加粗
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_Bold_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("bold", false, null);

		}
		/// <summary>
		/// 斜体
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_Italic_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("italic", false, null);
		}

		/// <summary>
		/// 下划线
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_Underline_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("underline", false, null);
		}

		/// <summary>
		/// 删除线
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_Strikethrough_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("strikethrough", false, null);
		}
		/// <summary>
		/// 清除格式
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_ClearFormat_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("removeformat", false, null);
		}
		/// <summary>
		/// 居左
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_JustifyLeft_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("Justifyleft", false, null);
		}
		/// <summary>
		/// 居中
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_JustifyCenter_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("JustifyCenter", false, null);
		}
		/// <summary>
		/// 居右
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_JustifyRight_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("JustifyRight", false, null);
		}

		/// <summary>
		/// 编号
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_OrderedList_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("Insertorderedlist", false, null);
		}
		/// <summary>
		/// 项目符号
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_UnorderedList_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("InsertUnorderedList", false, null);
		}
		/// <summary>
		/// 回退
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_Outdent_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("Outdent", false, null);
		}
		/// <summary>
		/// 缩进
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_Indent_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("Indent", false, null);
		}
		/// <summary>
		/// 上标
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_SuperScript_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("superscript", false, null);
		}
		/// <summary>
		/// 下标
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_SubScript_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("subscript", false, null);
		}
		/// <summary>
		/// 字体颜色
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_FontColor_Click(object sender, EventArgs e)
		{
			if (FontColor.ShowDialog() == DialogResult.OK)
			{
				ClippingHtml.execCommand("forecolor", true, string.Format("#{0}{1}{2}", FontColor.Color.R.ToString("X2"), FontColor.Color.G.ToString("X2"), FontColor.Color.B.ToString("X2")));
			}
		}
		/// <summary>
		/// 字体背景颜色
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_BgColor_Click(object sender, EventArgs e)
		{
			if (FontColor.ShowDialog() == DialogResult.OK)
			{
				ClippingHtml.execCommand("BackColor", false, string.Format("#{0}{1}{2}", FontColor.Color.R.ToString("X2"), FontColor.Color.G.ToString("X2"), FontColor.Color.B.ToString("X2")));
			}
		}
		/// <summary>
		/// 普通水平线
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_HorizontalRule_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("InsertHorizontalRule", false, null);
		}
		/// <summary>
		/// 插入超链接
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_Hyperlink_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("createlink", false, null);
		}
		/// <summary>
		/// 插入图片
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_Image_Click(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("InsertImage", true, null);
		}
		/// <summary>
		/// 插入日期
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_Date_Click(object sender, EventArgs e)
		{
			(ClippingHtml.selection.createRange() as mshtml.IHTMLTxtRange).pasteHTML(DateTime.Now.ToString("yyyy年MM月dd日"));
		}
		/// <summary>
		/// 设置字号
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TCB_FontSize_SelectedIndexChanged(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("fontsize", true, TCB_FontSize.Text);
		}
		/// <summary>
		/// 设置字体
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TCB_Font_SelectedIndexChanged(object sender, EventArgs e)
		{
			ClippingHtml.execCommand("fontname", true, TCB_Font.Text);
		}
		/// <summary>
		/// 插入表格
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_Table_Click(object sender, EventArgs e)
		{
			Dlg_InsertTable dit = Dlg_InsertTable.GetDialog();
			if (dit.ShowDialog() == DialogResult.OK)
			{
				(ClippingHtml.selection.createRange() as mshtml.IHTMLTxtRange).pasteHTML(dit.TableHtml);
			}
		}
		#endregion




		//public bool ConvertHtmlTextToMht(string htmlContent,string filePath)
		//{
		//    bool isConvertHtmlBytesToMht = false;
		//    CDO.Message  message = new CDO.MessageClass();
		//    ADODB.Stream  stream=null;
		//    message.MimeFormatted =true;
		//    message.HTMLBody = htmlContent;
		//    stream = message.GetStream();
		//    stream.Charset = "GB2312";
		//    string strMhtContent= stream.ReadText(stream.Size);
		//    byte[] BytMhtContent = Encoding.GetEncoding("GB2312").GetBytes(strMhtContent);
		//    File.WriteAllBytes(filePath, BytMhtContent);
		//    isConvertHtmlBytesToMht=true;
		//    return isConvertHtmlBytesToMht;
		//}

		#region 剪报工具
		/// <summary>
		/// 字数统计
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_TSMI_CountWords_Click(object sender, EventArgs e)
		{
			_controllist["字数"].PropertyValue = MyTools.NewsParser.CountWords(ClippingHtml.body.innerText).ToString();
		}
		/// <summary>
		/// 图片统计
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_TSMI_CountPic_Click(object sender, EventArgs e)
		{
			_controllist["图片数量"].PropertyValue = ClippingHtml.images.length.ToString();
		}
		/// <summary>
		/// 提取当前页正文
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_GetContent_Click(object sender, EventArgs e)
		{
			if (WB_NewsSite.Document == null || WB_NewsSite.Document.Body == null)
				return;
			string content;
			string channel;
			Uri nextpage;
			Cursor = Cursors.WaitCursor;
			MyTools.NewsParser.GetContent(WB_NewsSite.Url, WB_NewsSite.Document.Body.InnerHtml, 1, out content, out channel, out nextpage);
			if (ClippingHtml.body != null && content != null)
			{
				ClippingHtml.body.innerHTML = ClippingHtml.body.innerHTML + content;
				//TSB_InsertTitle_Click(null, null);
			}
			if (!string.IsNullOrEmpty(channel) && !_fullchannel)
			{
				int index = channel.LastIndexOf(">");
				if (index > 0 && index < channel.Length - 1)
				{
					channel = channel.Substring(index + 1);
					channel = channel.Trim();
				}
			}
			if (string.IsNullOrEmpty(_controllist["版面"].PropertyValue))
				_controllist["版面"].PropertyValue = channel;

			Cursor = Cursors.Default;
		}
		/// <summary>
		/// 提取连续页正文
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_GetContentSeriate_Click(object sender, EventArgs e)
		{
			string[] links = _controllist["链接"].Links;
			string link = null;
			if (links != null && links.Length > 0)
				link = links[0];
			if (Uri.IsWellFormedUriString(link, UriKind.Absolute))
			{
				Cursor = Cursors.WaitCursor;
				Uri uri = new Uri(link);
				string channel;
				string content = MyTools.NewsParser.GetContentContinuously(uri, out channel);
				if (ClippingHtml.body != null && content != null)
				{
					ClippingHtml.body.innerHTML = content;
					//TSB_InsertTitle_Click(null, null);
				}
				if (!string.IsNullOrEmpty(channel) && !_fullchannel)
				{
					int index = channel.LastIndexOf(">");
					if (index > 0 && index < channel.Length - 1)
					{
						channel = channel.Substring(index + 1);
						channel = channel.Trim();
					}
				}
				if (string.IsNullOrEmpty(_controllist["版面"].PropertyValue))
					_controllist["版面"].PropertyValue = channel;

				Cursor = Cursors.Default;
			}
			else
			{
				MessageBox.Show("不是一个格式良好的网页地址", "地址不正确", MessageBoxButtons.OK, MessageBoxIcon.Error);
				_controllist["链接"].Focus();

			}

		}

		/// <summary>
		/// 打开新闻页
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_OpenNewsSite_Click(object sender, EventArgs e)
		{

			string[] links = _controllist["链接"].Links;
			if (links != null && links.Length > 0)
				WB_NewsSite.Navigate(links[0]);
		}
		void cp_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Enter)
			{
				TSB_OpenNewsSite_Click(null, null);
			}
		}

		/// <summary>
		/// 插入标题
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_InsertTitle_Click(object sender, EventArgs e)
		{
			if (!string.IsNullOrEmpty(_controllist["标题"].PropertyValue))
			{
				if (ClippingHtml.body != null && ClippingHtml.body.innerHTML != null)
				{
					if (!Regex.Match(ClippingHtml.body.innerHTML, string.Format("^{0}", Regex.Escape("<p align=center>" + _controllist["标题"].PropertyValue + "</p>")), RegexOptions.IgnoreCase).Success)
					{
						ClippingHtml.body.innerHTML = string.Format("<p align=center>{0}</p>{1}", _controllist["标题"].PropertyValue, ClippingHtml.body.innerHTML);
					}
				}

			}
		}

		#endregion



		/// <summary>
		/// 上传剪报
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_UploadClipping_Click(object sender, EventArgs e)
		{
			//if (this._ftp == null)
			//{
			//    MessageBox.Show("未指定上传剪报的FTP，无法执行上传操作！");
			//    return;
			//}
			if (this._http == null)
			{
				MessageBox.Show("未指定上传剪报的HTTP，无法执行上传操作！");
				return;
			}
			if (this._selectedclass == null)
			{
				MessageBox.Show("未指定上传分类，无法执行上传操作！");
				return;
			}
			if (string.IsNullOrEmpty(_controllist["字数"].PropertyValue))
			{
				if (Properties.Settings.Default.AutoCountWords)
					TSB_TSMI_CountWords_Click(null, null);
				else
					_controllist["字数"].PropertyValue = "0";
			}
			if (_controllist.ContainsKey("Link"))
			{
				if (string.IsNullOrEmpty(_controllist["Link"].PropertyValue))
				{
					_controllist["Link"].PropertyValue = _controllist["链接"].PropertyValue;
				}
			}
			//if (_controllist.ContainsKey("link"))
			//{
			//    if (string.IsNullOrEmpty(_controllist["link"].PropertyValue))
			//    {
			//        _controllist["link"].PropertyValue = _controllist["链接"].PropertyValue;
			//    }
			//}
			if (!check())
				return;
			XmlDataDocument clippingxml = GenerateClipping();




			try
			{
				Cursor = Cursors.WaitCursor;
				WebClient wc = new WebClient();
				string url = _controllist["链接"].PropertyValue;

				string tmpFileName = string.Format("{0}{1}.xml", DateTime.Now.ToString("yyyyMMddhhmmss"), MyTools.Hash.md5Hash(url).Replace("-", ""));
				string tmpFilePath = Path.Combine(Application.StartupPath, tmpFileName);
				File.WriteAllText(tmpFilePath, clippingxml.InnerXml, _xmlFileEncoding);
				if (!string.IsNullOrEmpty(_http.XmlSavePath))
				{
					string remoteFileName = Path.Combine(_http.XmlSavePath, tmpFileName);
					File.Copy(tmpFilePath, remoteFileName);
				}
				if (!string.IsNullOrEmpty(_http.HttpAddress))
				{

					string uploadurl = string.Format("{0}?user={1}&pwd={2}", _http.HttpAddress.Trim('/'), _http.User, _http.Password);
					wc.Credentials = _http.Credential;
					wc.UploadFile(uploadurl, tmpFilePath);
					

					string[] links = _controllist["链接"].Links;
					if (links != null)
					{
						foreach (string l in links)
						{
							MyTools.UploadHistory.AddHistory(l);
						}
					}

					
					if (MessageBox.Show("剪报上传成功，是否关闭窗体？", "上传成功", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
					{
						this.Close();
					}
				}
				else
				{
					MessageBox.Show("请设置上传地址");
				}
				try
				{
					File.Delete(tmpFilePath);
				}
				catch (Exception ex)
				{ }



			}
			catch (Exception ex)
			{
				MessageBox.Show(string.Format("剪报上传失败：{0}{1}", Environment.NewLine, ex.Message));
			}
			finally
			{
				Cursor = Cursors.Default;
			}


		}

		private bool check()
		{
			if (string.IsNullOrEmpty(_controllist["标题"].PropertyValue.Trim()))
			{
				MessageBox.Show("请输入新闻标题。");
				_controllist["标题"].Focus();
				return false;
			}

			if (string.IsNullOrEmpty(_controllist["媒体"].PropertyValue.Trim()))
			{
				MessageBox.Show("请输入新闻媒体。");
				_controllist["媒体"].Focus();
				return false;
			}
			if (string.IsNullOrEmpty(_controllist["日期"].PropertyValue.Trim()))
			{
				MessageBox.Show("请输入新闻日期。");
				_controllist["日期"].Focus();
				return false;
			}
			int words;
			if (!int.TryParse(_controllist["字数"].PropertyValue, out words))
			{
				MessageBox.Show("字数必须是数字。");
				_controllist["字数"].Focus();
				return false;
			}


			string dt = _controllist["日期"].PropertyValue;
			DateTime date;
			if (!DateTime.TryParse(_controllist["日期"].PropertyValue, out date) || !Regex.IsMatch(dt, @"^\d{4}-\d{1,2}-\d{1,2}( \d{2}:\d{2}:\d{2}| \d{2}:\d{2})?$"))
			{
				MessageBox.Show("不是有效的日期格式。");
				_controllist["日期"].Focus();
				return false;
			}
			string pagesize = _controllist["页面大小"].PropertyValue;
			if (!Regex.IsMatch(pagesize, @"^\d+/\d+$"))
			{
				MessageBox.Show("页面大小的格式不正确。\n请输入形如 “1/1”，“1/2”，“1/3”...的内容。");
				_controllist["页面大小"].Focus();
				return false;
			}

			string height = _controllist["高度"].PropertyValue;

			if (!Regex.IsMatch(height, @"^\d+(\.\d+)?$"))
			{
				MessageBox.Show("高度的格式不正确。\n请输入数字。");
				_controllist["高度"].Focus();
				return false;
			}

			string width = _controllist["宽度"].PropertyValue;
			if (!Regex.IsMatch(width, @"^\d+(\.\d+)?$"))
			{
				MessageBox.Show("宽度的格式不正确。\n请输入数字。");
				_controllist["宽度"].Focus();
				return false;
			}
			foreach (Property p in this._selectedclient.Properties)
			{
				if (string.IsNullOrEmpty(_controllist[p.Name].PropertyValue))
				{
					MessageBox.Show(string.Format("{0} 不能为空！", p.Name));
					_controllist[p.Name].Focus();
					return false;
				}

			}
			return true;
		}
		private XmlDataDocument GenerateClipping()
		{
			XmlDataDocument xmldoc = new XmlDataDocument();
			xmldoc.LoadXml(XMLTEMPLATE);
			XmlElement xe;
			XmlNode rootnode = xmldoc.SelectSingleNode("/Clipping");
			xe = rootnode as XmlElement;
			xe.SetAttribute("ClientId", this._selectedclient.Id);



			xe = xmldoc.CreateNode(XmlNodeType.Element, "Classes", "") as XmlElement;
			foreach (ClassInfo ci in this._selectedclass)
			{
				XmlNode subNode = xmldoc.CreateNode(XmlNodeType.Element, "Class", "");
				XmlNode valueNode = xmldoc.CreateNode(XmlNodeType.Text, "ValueClass", "");
				valueNode.Value = ci.Id;
				subNode.AppendChild(valueNode);
				xe.AppendChild(subNode);

			}
			rootnode.AppendChild(xe);



			ClippingProperty cp;
			foreach (Control c in tableLayoutPanel1.Controls)
			{
				cp = c as ClippingProperty;
				if (cp != null)
				{
					if (cp.Type == PropertyType.Link)
					{
						xe = xmldoc.CreateNode(XmlNodeType.Element, "Links", "") as XmlElement;
						string[] links = cp.Links;
						if (links != null)
						{
							foreach (string l in links)
							{
								XmlNode subNode = xmldoc.CreateNode(XmlNodeType.Element, "Link", "");
								XmlNode valueNode = xmldoc.CreateNode(XmlNodeType.Text, "linkValue", "");
								valueNode.Value = l;
								subNode.AppendChild(valueNode);
								xe.AppendChild(subNode);
							}

						}
						rootnode.AppendChild(xe);
					}
					else
					{
						xe = xmldoc.CreateNode(XmlNodeType.Element, "Field", "") as XmlElement;
						xe.SetAttribute("Name", cp.PropertyName);
						xe.SetAttribute("Value", cp.PropertyValue);
						rootnode.AppendChild(xe);
					}

				}
			}
			foreach (Control c in this.flowLayoutPanel_PublicFields.Controls)
			{
				cp = c as ClippingProperty;
				if (cp != null)
				{
					if (cp.Type == PropertyType.Field)
					{
						xe = xmldoc.CreateNode(XmlNodeType.Element, "Field", "") as XmlElement;
						xe.SetAttribute("Name", cp.PropertyName);
						xe.SetAttribute("Value", cp.PropertyValue);
					}
					else if (cp.Type == PropertyType.Property)
					{
						xe = xmldoc.CreateNode(XmlNodeType.Element, "Property", "") as XmlElement;
						xe.SetAttribute("Name", cp.PropertyName);
						xe.SetAttribute("Value", cp.PropertyValue);
					}

					rootnode.AppendChild(xe);

				}
			}

			xe = xmldoc.CreateNode(XmlNodeType.Element, "Field", "") as XmlElement;
			xe.SetAttribute("Name", "addedBy");
			xe.SetAttribute("Value", _currentuser.Id);
			rootnode.AppendChild(xe);

			foreach (Control c in this.flowLayoutPanel_ProfileFields.Controls)
			{
				cp = c as ClippingProperty;
				if (cp != null)
				{
					if (cp.Type == PropertyType.Field)
					{
						xe = xmldoc.CreateNode(XmlNodeType.Element, "Field", "") as XmlElement;
						xe.SetAttribute("Name", cp.PropertyName);
						xe.SetAttribute("Value", cp.PropertyValue);
					}
					else
					{
						xe = xmldoc.CreateNode(XmlNodeType.Element, "Property", "") as XmlElement;
						xe.SetAttribute("Name", cp.PropertyName);
						xe.SetAttribute("Value", cp.PropertyValue);
					}
					rootnode.AppendChild(xe);
				}
			}
			foreach (Control c in this.flowLayoutPanel_MultiSelectProperty.Controls)
			{
				cp = c as ClippingProperty;
				if (cp != null)
				{
					if (cp.Type == PropertyType.Field)
					{
						xe = xmldoc.CreateNode(XmlNodeType.Element, "Field", "") as XmlElement;
						xe.SetAttribute("Name", cp.PropertyName);
						xe.SetAttribute("Value", cp.PropertyValue);
					}
					else
					{
						xe = xmldoc.CreateNode(XmlNodeType.Element, "Property", "") as XmlElement;
						xe.SetAttribute("Name", cp.PropertyName);
						xe.SetAttribute("Value", cp.PropertyValue);
					}
					rootnode.AppendChild(xe);
				}
			}
			foreach (ListViewItem lvi in this.listView_CapPictures.Items)
			{
				Bitmap bitmap = lvi.Tag as Bitmap;
				string picbase64 = getBase64Pic(bitmap);
				xe = xmldoc.CreateNode(XmlNodeType.Element, "Pic", "") as XmlElement;
				XmlCDataSection picdata = xmldoc.CreateCDataSection(picbase64);
				xe.AppendChild(picdata);
				xmldoc.SelectSingleNode("/Clipping/CapPictures").AppendChild(xe);
			}

			string html = ClippingHtml.body.innerHTML;
			if (html == null)
				html = "";
			string txt = ClippingHtml.body.innerText;
			XmlCDataSection cdata = xmldoc.CreateCDataSection(html);
			xmldoc.SelectSingleNode("/Clipping/ContentHtml").AppendChild(cdata);
			cdata = xmldoc.CreateCDataSection(txt);
			xmldoc.SelectSingleNode("/Clipping/ContentTxt").AppendChild(cdata);
			foreach (Match m in Regex.Matches(html, "<img\\s+[^>]*?src=[\"\']?([^\">]+)[\"\']?[^>]*>", RegexOptions.IgnoreCase))
			{
				try
				{
					string link = null;
					string[] links = _controllist["链接"].Links;
					if (links != null && links.Length > 0)
						link = links[0];
					string picbase64 = getBase64Pic(m.Groups[1].Value, link);
					xe = xmldoc.CreateNode(XmlNodeType.Element, "Pic", "") as XmlElement;
					XmlCDataSection picdata = xmldoc.CreateCDataSection(picbase64);
					xe.SetAttribute("url", m.Groups[1].Value);
					xe.AppendChild(picdata);
					xmldoc.SelectSingleNode("/Clipping/Pictures").AppendChild(xe);
				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.Message);
				}
			}

			return xmldoc;
		}

		private string getBase64Pic(string picUrl, string refererUrl)
		{
			if (string.IsNullOrEmpty(picUrl))
				return "";
			WebClient wc = new WebClient();
			wc.Headers.Add(HttpRequestHeader.Referer, refererUrl);
			wc.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.CacheIfAvailable);
			try
			{
				byte[] data = wc.DownloadData(picUrl);
				if (data.Length > 0)
					return Convert.ToBase64String(data);
				else
					return "";
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}
		private string getBase64Pic(Bitmap bitmap)
		{
			System.IO.MemoryStream stream = new System.IO.MemoryStream();
			bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
			byte[] imageBytes = stream.ToArray();
			string base64String = Convert.ToBase64String(imageBytes);
			return base64String;
		}



		#region 浏览器导航
		/// <summary>
		/// 设置前进后退按钮可用性
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void WB_NewsSite_Navigated(object sender, WebBrowserNavigatedEventArgs e)
		{
			TSB_Back.Enabled = WB_NewsSite.CanGoBack;
			TSB_Forward.Enabled = WB_NewsSite.CanGoForward;
		}
		/// <summary>
		/// 后退
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_Back_Click(object sender, EventArgs e)
		{
			if (WB_NewsSite.CanGoBack)
				WB_NewsSite.GoBack();
		}
		/// <summary>
		/// 前进
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_Forward_Click(object sender, EventArgs e)
		{
			if (WB_NewsSite.CanGoForward)
				WB_NewsSite.GoForward();
		}
		/// <summary>
		/// 刷新
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_Refresh_Click(object sender, EventArgs e)
		{
			WB_NewsSite.Refresh();
		}
		/// <summary>
		/// 停止
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_Stop_Click(object sender, EventArgs e)
		{
			WB_NewsSite.Stop();
		}
		#endregion



		/// <summary>
		/// 获取或设置FTP信息
		/// </summary>
		public FtpInfo Ftp
		{
			get { return _ftp; }
			set { _ftp = value; }
		}

		private void toolStrip_SelectClass_Resize(object sender, EventArgs e)
		{
			if (toolStrip_SelectClass.Size.Width > 300)
			{
				TSB_SelectedClass.Size = new Size(toolStrip_SelectClass.Size.Width - 100, TSB_SelectedClass.Size.Height);
			}
			else
			{
				TSB_SelectedClass.Size = new Size(100, TSB_SelectedClass.Size.Height);
			}
		}

		/// <summary>
		/// 选择上传分类
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSB_SelectClass_Click(object sender, EventArgs e)
		{
			if (this._currentuser == null)
			{
				MessageBox.Show("尚未设置用户信息，无法取得分类列表！");
				return;
			}
			Dlg_SelectClient dlg = Dlg_SelectClient.GetDialog(this._currentuser.Clients);
			dlg.ClearSelectedCategory();
			if (dlg.ShowDialog() == DialogResult.OK)
			{
				if (this._selectedclass != dlg.SelectedClass)
				{
					this._selectedclass = dlg.SelectedClass;
					List<string> s = new List<string>();
					foreach (ClassInfo ci in _selectedclass)
						s.Add(ci.FullPath);

					this.TSB_SelectedClass.Text = string.Join("; ", s.ToArray());
				}
				if (this._selectedclient != dlg.SelectedClient)
				{
					this._selectedclient = dlg.SelectedClient;

					loadProfileControls();
				}
			}
		}

		/// <summary>
		/// 加载个性化字段控件
		/// </summary>
		private void loadProfileControls()
		{
			ClippingProperty oldp;
			foreach (Control c in flowLayoutPanel_ProfileFields.Controls)
			{
				oldp = c as ClippingProperty;
				if (oldp != null)
				{
					if (this._controllist.ContainsKey(oldp.PropertyName))
					{
						this._controllist.Remove(oldp.PropertyName);
					}
				}

			}
			foreach (Control c in flowLayoutPanel_MultiSelectProperty.Controls)
			{
				oldp = c as ClippingProperty;
				if (oldp != null)
				{
					if (this._controllist.ContainsKey(oldp.PropertyName))
					{
						this._controllist.Remove(oldp.PropertyName);
					}
				}

			}


			flowLayoutPanel_ProfileFields.Controls.Clear();
			flowLayoutPanel_MultiSelectProperty.Controls.Clear();

			foreach (Field f in this._selectedclient.Fields)
			{
				ClippingProperty cp = new ClippingProperty(f.Name, f.Name);
				cp.Width = 200;
				this.flowLayoutPanel_ProfileFields.Controls.Add(cp);
				this._controllist.Add(f.Name, cp);
			}
			foreach (Property p in this._selectedclient.Properties)
			{
				if (p.MultiSelect == false)
				{
					ClippingProperty cp = new ClippingProperty(p.Name, p.Name, p.Options, false);
					cp.Width = 200;
					this.flowLayoutPanel_ProfileFields.Controls.Add(cp);
					this._controllist.Add(p.Name, cp);
				}
				else
				{
					ClippingProperty cp = new ClippingProperty(p.Name, p.Name, p.Options, true);


					if (this.flowLayoutPanel_MultiSelectProperty.Width > 10)
						cp.Width = this.flowLayoutPanel_MultiSelectProperty.Width - 10;

					//int itemsPerRow = cp.Width / 106;
					//int rowCount = p.Options.Count / itemsPerRow;
					//if (p.Options.Count % itemsPerRow > 0)
					//    rowCount += 1;
					//cp.Height = 28*rowCount ;
					cp.Height = cp.getDesiredHeight();

					cp.SizeChanged -= new EventHandler(cp_SizeChanged);
					cp.SizeChanged += new EventHandler(cp_SizeChanged);
					this.flowLayoutPanel_MultiSelectProperty.Controls.Add(cp);
					this._controllist.Add(p.Name, cp);

				}
			}
		}

		void cp_SizeChanged(object sender, EventArgs e)
		{
			int totalHeight = 0;
			foreach (Control control in this.flowLayoutPanel_MultiSelectProperty.Controls)
			{
				totalHeight += control.Height + 4;
			}
			if (this.flowLayoutPanel_MultiSelectProperty.Height < totalHeight)
				this.flowLayoutPanel_MultiSelectProperty.Height = totalHeight;
		}


		/// <summary>
		/// 显示选项对话框
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TSMI_Options_Click(object sender, EventArgs e)
		{
			Dlg_Options dlg = new Dlg_Options();
			dlg.ShowDialog();
		}

		private void flowLayoutPanel_MultiSelectProperty_SizeChanged(object sender, EventArgs e)
		{
			foreach (Control control in this.flowLayoutPanel_MultiSelectProperty.Controls)
			{
				ClippingProperty cp = control as ClippingProperty;
				if (cp != null && cp.Options != null)
				{
					control.Width = this.flowLayoutPanel_MultiSelectProperty.Width - 10;
					//int itemsPerRow = cp.Width / 106;
					//int rowCount = cp.Options.Count / itemsPerRow;
					//if (cp.Options.Count % itemsPerRow > 0)
					//    rowCount += 1;
					//cp.Height = 28 * rowCount;
					cp.Height = cp.getDesiredHeight();
				}
			}

		}

		private void TSB_ConvertToImage_Click(object sender, EventArgs e)
		{
			string[] links = _controllist["链接"].Links;
			string url = null;
			if (links != null && links.Length > 0)
				url = links[0];
			TabControl1.SelectedIndex = 2;
			Dlg_ImageEditor dlg = new Dlg_ImageEditor(url, addCapPicture);
			dlg.Show();
		}

		private void addCapPicture(Bitmap bitmap)
		{
			string key = bitmap.GetHashCode().ToString();
			this.imageList_CapPictures.Images.Add(key, bitmap);
			ListViewItem lvi = new ListViewItem();
			lvi.Tag = bitmap;
			lvi.ImageKey = key;
			this.listView_CapPictures.Items.Add(lvi);
			if (this.listView_CapPictures.SelectedItems.Count == 0)
				lvi.Selected = true;
		}


		private void toolStripMenuItem_DelCapPic_Click(object sender, EventArgs e)
		{
			if (this.listView_CapPictures.SelectedItems.Count == 0)
				return;
			List<ListViewItem> itemsToDel = new List<ListViewItem>();
			foreach (var item in this.listView_CapPictures.SelectedItems)
			{
				itemsToDel.Add(item as ListViewItem);
			}
			foreach (var item in itemsToDel)
			{
				this.listView_CapPictures.Items.Remove(item);
				Bitmap img = item.Tag as Bitmap;
				string key = img.GetHashCode().ToString();
				this.imageList_CapPictures.Images.RemoveByKey(key);
			}
			if (this.listView_CapPictures.Items.Count > 0)
			{
				this.listView_CapPictures.Items[0].Selected = true;
			}
			else
			{

			}
		}

		private void btn_AddLocalPic_Click(object sender, EventArgs e)
		{
			OpenFileDialog dlg = new OpenFileDialog();
			dlg.Filter = "所有图片文件|*.png;*.jpg;*.jpeg;*.gif;*.bmp|PNG(*.png)|*.png|JPEG(*.jpg;*.jpeg)|*.jpg;*.jpeg|GIF(*.gif)|*.gif|BMP(*.bmp)|*.bmp";
			dlg.Multiselect = true;
			var result = dlg.ShowDialog();
			if (result == System.Windows.Forms.DialogResult.OK)
			{
				foreach (var file in dlg.FileNames)
				{
					try
					{
						Bitmap bitmap = new Bitmap(file);
						addCapPicture(bitmap);
					}
					catch (Exception ex)
					{
						MessageBox.Show(ex.Message);
					}
				}


			}
		}

		private void listView_CapPictures_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			if (e.Button == MouseButtons.Left)
			{
				ListViewHitTestInfo lvhti = this.listView_CapPictures.HitTest(e.Location);
				ListViewItem lvi = lvhti.Item;
				if (lvi != null)
				{
					editPic(lvi);


				}
			}
		}
		private void toolStripMenuItem_Edit_Click(object sender, EventArgs e)
		{
			if (this.listView_CapPictures.SelectedItems != null && this.listView_CapPictures.SelectedItems.Count > 0)
			{
				var lvi = this.listView_CapPictures.SelectedItems[0];
				editPic(lvi);
			}
		}
		private void editPic(ListViewItem lvi)
		{
			Bitmap img = lvi.Tag as Bitmap;
			string key = img.GetHashCode().ToString();
			if (img != null)
			{
				Dlg_ImageEditor dlg = new Dlg_ImageEditor(img, bitmap =>
				{
					lvi.Tag = bitmap;

					this.imageList_CapPictures.Images.RemoveByKey(key);
					key = bitmap.GetHashCode().ToString();
					this.imageList_CapPictures.Images.Add(key, bitmap);
					lvi.ImageKey = key;
					listView_CapPictures_ItemSelectionChanged(null, null);
				});
				dlg.Text = "图片编辑";
				dlg.ShowDialog();
			}
		}

		private void listView_CapPictures_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
		{
			if (this.listView_CapPictures.SelectedItems.Count > 0)
			{
				Bitmap img = this.listView_CapPictures.SelectedItems[0].Tag as Bitmap;
				if (img != null)
					this.pictureBox1.Image = img;
			}
			else
				this.pictureBox1.Image = null;
		}

		private void pictureBox1_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			Image img = pictureBox1.Image;
			if (img == null)
				return;
			foreach (ListViewItem lvi in this.listView_CapPictures.Items)
			{
				if (lvi.Tag == img)
				{
					editPic(lvi);
					break;
				}
			}
		}



        /// <summary>
        /// 设置序列化xml时所用的编码
        /// </summary>
        /// <param name="encoding"></param>
        public static void SetXmlFileEncoding(Encoding encoding)
        {
            if (_xmlFileEncoding.WebName != encoding.WebName)
            {
                _xmlFileEncoding = encoding;
                initXmlTemplate();
            }
        }


	}
}
